﻿using System.Diagnostics;
using Hippo.Framework.Model;

namespace Hippo.Agent.Lib.Runner
{
    using System;
    using Hippo.Framework;

    public abstract class TestRunner
    {
        public event EventHandler<EventArgs> TestStarting;

        public event EventHandler<EventArgs> TestFinished;

        public virtual TestResult Execute(TestBase test)
        {
            var result = new TestResult(Environment.MachineName, test.Name);
            var watch = new Stopwatch();

            try
            {
                InvokeTestStarting(EventArgs.Empty);
                watch.Start();

                /* Run test */
                test.Run();
                result.Success = true;
            }
            catch (Exception)
            {
                result.Success = false;
            }
            finally
            {
                watch.Stop();
                result.ElapsedMilliseconds = watch.ElapsedMilliseconds;
                
                InvokeTestFinished(EventArgs.Empty);
            }

            return result;
        }

        private void InvokeTestStarting(EventArgs e)
        {
            var handler = TestStarting;
            if (handler != null)
            {
                handler(this, e);
            }
        }
        public void InvokeTestFinished(EventArgs e)
        {
            var handler = TestFinished;
            if (handler != null)
            {
                handler(this, e);
            }
        }
    }
}
